package com.jhws.core.shiro.realms;

import com.jhws.common.base.bo.Global;
import com.jhws.util.LogHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * Created by Alex Tan on 2017/4/14.
 */
public class CustomRealm extends AuthorizingRealm {

    /*
        为了节省效率，通过创建custom专用的token, 并重写supports接口，
        可以做到只有custom认证才会调用此realm中的认证接口
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        if("CustomAuthToken".equals(token.getClass().getSimpleName()))
            return true;
        return false;
    }

    /*
        获取Custom角色信息，默认为物管
        sesstion注册时写入了一个loginType, 因此只有custom认证才能调用这个权限接口
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        LogHelper.getLogger().debug("custom doGetAuthorizationInfo ");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if("custom".equals(SecurityUtils.getSubject().getSession().getAttribute("loginType")))
            info.addRole(Global.ROLE_PROPERTY_ADMIN);
        return info;
    }

    /*
        获取custom认证信息
        由于custom认证在Filter中已经通过头部进行认证，这里的信息都是随便填的
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        LogHelper.getLogger().debug("custom username "+username);
        return new SimpleAuthenticationInfo("customer", //用户名
                "none", //密码
                ByteSource.Util.bytes("hehe"),//salt=username+salt
                getName() );
    }
}
